<template>
  <div class="body">
    <div class="Loading" v-if="aspin">
      <a-spin dot />
    </div>
    <div class="body-logo">
      <img :src="logoUrl" alt="" />
    </div>
    <div class="bodylogin">
      <div class="body-left">
        <img class="imgbody" src="/img/login.png" alt="" />
      </div>
      <div class="body-right">
        <div class="body-top">{{ organTitle }}</div>
        <div class="body-fome">
          <div class="body-list" v-if="logintrue">
            <a-form :model="form" :rules="rules" class="formlist" layout="vertical" ref="loingform">
              <a-form-item field="username" label="账号" required>
                <a-input v-model="form.username" max-length="25" placeholder="请输入账号"
                  @input="handleInput('1', $event)" />
              </a-form-item>
              <a-form-item field="password" label="密码" required>
                <a-input-password v-model="form.password" @input="handleInput('2', $event)" max-length="25"
                  placeholder="请输入密码" />
              </a-form-item>
              <a-form-item field="captcha" label="验证码" required>
                <a-row class="grid-demo">
                  <a-col :span="12">
                    <a-input v-model="form.captcha" @input="handleInput('3', $event)" placeholder="验证码" />
                  </a-col>
                  <a-col :span="12">
                    <div class="imgsdiv" @click="iconemail">
                      <img :src="imgs" alt="" />
                      <!-- <icon-refresh
                        @click="iconemail"
                      /> -->
                    </div>
                  </a-col>
                </a-row>
              </a-form-item>
              <a-form-item>
                <div class="button">
                  <a-button class="button" type="primary" @click="loginashore">登陆</a-button>
                </div>
              </a-form-item>
              <!-- <a-form-item>
                <div class="zhuce" @click="register(1)">没有账号，去注册</div>
              </a-form-item> -->
            </a-form>
          </div>

          <div class="listname" v-if="!logintrue">
            <a-form :model="formdata" :rules="rulesdata" layout="vertical" ref="formRef" class="formlist">
              <a-form-item field="area" :hide-asterisk="true">
                <a-cascader :options="cascaderData" class="cascader" placeholder="地区" :default-value="formdata.area"
                  v-model="formdata.area" :path-mode="true" @change="handleChange" />
              </a-form-item>

              <a-form-item field="grade" :hide-asterisk="true">
                <a-select v-model="formdata.grade" placeholder="请选择年级">
                  <a-option v-for="item of gradeyear" :value="item.GradeID" :label="item.GradeName" :key="item" />
                </a-select>
              </a-form-item>
              <a-form-item field="realName" :hide-asterisk="true" required>
                <a-input v-model="formdata.realName" placeholder="请输入姓名" />
              </a-form-item>
              <a-form-item field="userName" :hide-asterisk="true" validate-trigger="blur" required>
                <a-input v-model="formdata.userName" placeholder="请输入手机号" :max-length="11"
                  @input="handleInput('4', $event)" allow-clear>
                  <template #prepend> +86 </template>
                </a-input>
              </a-form-item>
              <a-form-item field="passWord" :hide-asterisk="true" required>
                <a-input-password v-model="formdata.passWord" placeholder="请输入密码" :max-length="11"
                  @input="handleInput('5', $event)" />
              </a-form-item>
              <a-form-item field="passWord1" :hide-asterisk="true" required>
                <a-input-password v-model="formdata.passWord1" placeholder="请重新输入密码" :max-length="11"
                  @input="handleInput('6', $event)" />
              </a-form-item>
              <a-form-item field="invitation" :hide-asterisk="true">
                <a-input v-model="formdata.invitation" placeholder="请输入激活码(选填)" :max-length="15" />
              </a-form-item>
              <a-form-item field="captcha" :hide-asterisk="true" validate-trigger="blur">
                <a-row class="grid-demo">
                  <a-col :span="12">
                    <a-input v-model="formdata.captcha" @input="handleInput('7', $event)" placeholder="验证码" />
                  </a-col>
                  <a-col :span="12">
                    <div class="imgsdiv" @click="iconemail">
                      <img :src="imgs" alt="" />
                      <!-- <icon-refresh
                        @click="iconemail"
                      /> -->
                    </div>
                  </a-col>
                </a-row>
              </a-form-item>
              <a-form-item>
                <div class="button">
                  <a-button class="button" type="primary" @click="registration">注册</a-button>
                </div>
              </a-form-item>
              <a-form-item>
                <div class="zhuce" @click="register(2)">已有账号，去登陆</div>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";
import { FormInstance } from "@arco-design/web-vue/es/form";
import { setToken, setPermission } from "@/utils/auth";
import { Message, Modal } from "@arco-design/web-vue";
import useUserStore from "../../store/modules/user"; // 根据实际路径修改
import {
  loginlogin,
  registercaptcha,
  postregister,
  getregisterAreas,
  logingetGrade,
  getOrgInfoData,
  getConfig
} from "../../api/login";
// 获取用户存储实例
const userStore = useUserStore();
const router = useRouter();
const logintrue = ref(true);
// 获取表单引用
const formRef = ref<FormInstance>();
const myArray = ref<any[]>([]);
// 原始数据结构（示例数据，需要替换为完整数据）
// 1. 定义 reactive 对象
const rawData = reactive<Record<string, any[]>>({});
// 类型定义
interface AreaNode {
  value: string;
  label: string;
  children?: AreaNode[];
  isLeaf?: boolean; // 添加末级标记
}

// 将原始数据转换为Cascader需要的树形结构
const cascaderData = computed(() => {
  const buildTree = (parentId: string): AreaNode[] => {
    return (rawData[parentId] || []).map((item) => ({
      value: item.AreaID,
      label: item.AreaName,
      // children: buildTree(item.AreaID),

      isLeaf: item.Last === 1, // 根据Last字段标记是否为末级
      children: item.Last === 1 ? undefined : buildTree(item.AreaID), // 末级节点不构建children
    }));
  };
  return buildTree("0");
});


// 处理选择变化
const handleChange = (value: string[]) => {
  console.log("Selected AreaIDs:", value);
  // 如果需要获取完整对象，可以在这里添加查找逻辑
};

const gradeyear = ref<any[]>([]);
const form = reactive({
  username: "",
  password: "",
  captcha: "",
});

const formdata = reactive({
  area: [] as string[], // 保存选中路径的AreaID数组
  grade: "",
  realName: "",
  userName: "",
  passWord: "",
  passWord1: "",
  captcha: "",
  invitation: "",
});
const rules = {
  username: [
    {
      required: true,
      message: "请输入账号",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
    },
  ],
  captcha: [
    {
      required: true,
      message: "请输入验证码",
    },
  ],
};
const rulesdata = {
  area: [
    {
      required: true,
      message: "请选择地区",
    },
  ],
  grade: [
    {
      required: true,
      message: "请选择年级",
    },
  ],
  realName: [
    {
      required: true,
      message: "请输入真实姓名",
    },
  ],
  userName: [
    {
      required: true,
      message: "请输入用户名",
    },
  ],
  passWord: [
    {
      required: true,
      message: "请输入密码",
    },
  ],
  passWord1: [
    {
      required: true,
      message: "请输入密码",
    },
  ],
  captcha: [
    {
      required: true,
      message: "请输入验证码",
    },
    // {
    //   required: true,
    //   validator: (rule: any, value: any) => {

    //     if (!/^1[3-9]\d{9}$/.test(value)) {

    //       return Promise.reject(Message.error("手机号格式不正确"));
    //     }
    //     return Promise.resolve();
    //   },
    //   trigger: "blur",
    // },
  ],
};

// const handleChange = (value: string[]) => {
//   const labels: string[] = [];
//   let currentOptions = myArray.value;
//   for (let i = 0; i < value.length; i++) {
//     const currentValue = value[i];
//     const option = currentOptions.find((item) => item.value === currentValue);
//     if (option) {
//       labels.push(option.label as string);
//       if (option.children) {
//         currentOptions = option.children;
//       }
//     }
//   }

//   formdata.area = labels.join("");
// };
const imgs = ref();
const aspin = ref(false);
const logoUrl = ref(); // 替换为实际的logo路径
const organTitle = ref(); // 替换为实际的机构名称
const iconemail = () => {
  imgregistercaptcha();
};
// 验证码
const imgregistercaptcha = () => {
  registercaptcha().then((res: any) => {
    imgs.value = res.img;
  });
};
// const RefundReadForm = reactive({
//   subjectId: subjectID,
// });
const getOrgInfo = () => {
  const urlParams = new URLSearchParams(window.location.search)
  const code = urlParams.get('code');
  logoUrl.value = "/img/denglu.png";
  // organTitle.value = "欢迎来到榜眼邦";
  getConfig().then((res: any) => {
    organTitle.value = "欢迎来到"+res[0].Website_default || "欢迎来到榜眼邦";
    document.title = res[0].Website_default;
    localStorage.setItem("webtitle", res[0].Website_default);
  });
  // getOrgInfoData(code).then((res: any) => {
  //   // logoUrl.value = res.url || "/img/denglu.png";
  //   organTitle.value = "欢迎来到榜眼邦";
  // });
};
const loingform = ref<FormInstance>();

const setFieldValue = {
  1: (value: any) => (form.username = value),
  2: (value: any) => (form.password = value),
  3: (value: any) => (form.captcha = value),
  4: (value: any) => (formdata.userName = value),
  5: (value: any) => (formdata.passWord = value),
  6: (value: any) => (formdata.passWord1 = value),
  7: (value: any) => (formdata.captcha = value),
  8: (value: any) => (formdata.realName = value),
};
const handleInput = (index: any, e: any) => {
  const cleanValue = e.replace(/\s/g, "");
  const setValue = setFieldValue[index];
  if (setValue) {
    setValue(cleanValue);
  }
  // if (index == 1) {
  //   form.username = e.replace(/\s/g, "");
  // } else if (index == 2) {
  //   form.password = e.replace(/\s/g, "");
  // } else if (index == 3) {
  //   form.captcha = e.replace(/\s/g, "");
  // }else if (index == 4){
  //   formdata.userName = e.replace(/\s/g, "");
  // }else if (index==5){
  //   formdata.passWord =  e.replace(/\s/g, "");
  // } else if (index == 6) {
  //   formdata.passWord1 = e.replace(/\s/g, "");
  // } else if (index == 7){
  //   formdata.captcha =   e.replace(/\s/g, "");
  // }
};
// 处理登录逻辑
const loginashore = async () => {
  const res = await loingform.value?.validate();

  if (!res) {
    aspin.value = true;
    try {
      // 调用 login 方法进行登录
      await userStore.login(form);
      // 登录成功后的操作，例如跳转到主页
      // aspin.value = false;
      router.push({
        name: "/home",
      });
      (form.username = ""), (form.password = ""), (form.captcha = "");
      aspin.value = false;
    } catch (error) {
      aspin.value = false;
      // router.push({
      //   name: "/home",
      // });
      // 登录失败的处理
      console.error("登录失败:", error);
      imgregistercaptcha();
    }
  }
};

// 登录
// const loginashore = async () => {
//   const res = await loingform.value?.validate();
//   if (!res) {
//     loginlogin(form).then((res: any) => {

//       setToken(res.code);
//       setPermission(res);
//       router.push({
//         name: "/home",
//       });
//     });
//   }
// };
//切换
const register = (e: any) => {
  logintrue.value = !logintrue.value;
  if (e == 1) {
    area(); //地区
    gradelist(); //年级
  }
};

// 递归转换函数
const convertData = (data: any[]) => {
  return data.map((item) => {
    const newItem: any = {
      value: item.AreaID,
      label: item.AreaName,
      Last: item.Last,
    };
    if (item.child) {
      // 处理 child 是数组嵌套的情况
      const processedChildren = item.child
        .map((subChild: any) => {
          if (Array.isArray(subChild)) {
            return convertData(subChild);
          }
          return convertData([subChild]);
        })
        .flat();
      newItem.children = processedChildren;
    }
    return newItem;
  });
};
//获取地区

const area = () => {
  getregisterAreas().then((res) => {
    // if (Array.isArray(res)) {
    //   const convertedData = convertData(res);
    //   // myArray.value = convertedData;
    //    // 方法 2：使用 Object.assign（适用于浅层数据）
    // Object.assign(rawData, convertedData);
    // } else {
    //   console.error("返回的数据不是数组类型:", res);
    // }
    // const convertedData = convertData(res);
    Object.assign(rawData, res);
  });
};
const gradelist = () => {
  logingetGrade().then((res: any) => {
    gradeyear.value = res;
  });
};

// 表单提交处理函数
const registration = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    postregister(formdata).then((res: any) => {
      formdata.area = "";
      formdata.grade = "";
      formdata.realName = "";
      formdata.userName = "";
      formdata.passWord = "";
      formdata.passWord1 = "";
      formdata.captcha = "";
      formdata.invitation = "";
      Message.success("注册成功");
      logintrue.value = !logintrue.value;
    });
    imgregistercaptcha();
  }
};
// 在setup()中
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.keyCode === 13) {
    // 13是回车键的keyCode
    loginashore();
  }
};

onMounted(() => {
  imgregistercaptcha(); //验证码
  getOrgInfo();//获取机构信息

  // 添加键盘事件监听
  window.addEventListener("keypress", handleKeyPress);
});
onUnmounted(() => {
  // 组件卸载时移除监听，避免内存泄漏
  window.removeEventListener("keypress", handleKeyPress);
});
</script>
<style lang="less" scoped>
:deep.arco-form-item {
  margin-bottom: 0px;
}

.body-logo {
  position: absolute;
  top: 2vw;
  left: 2vw;

  // background-color: pink;
  img {
    width: 8vw;
    // height: 2.5vw;
    // background-color: pink;
    // object-fit: cover;
  }
}

.spinnu {
  position: fixed;
  left: 45%;
  top: 50%;
}

.body {
  width: 99vw;
  height: 98vh;
  // position: relative;
  background: #f7fbff;
  display: flex;
  justify-content: center;
  align-items: center;

  .bodylogin {
    width: 70vw;
    // height: 75vh;
    border-radius: 2vw;
    background: #f7fbff;
    // .bodylogin{// }
    display: flex;

    .body-left {
      width: 60%;
      height: 100%;
      border-radius: 2vw 0 0 2vw;

      .imgbody {
        width: 100%;
        height: 100%;
      }

      // background-color: blue;
    }

    .body-right {
      width: 40%;
      // height: 100%;
      padding: 3vw 3vw 0 3vw;
      border-radius: 0vw 2vw 2vw 0vw;
      background-color: #fff;

      .body-top {
        font-size: 1.5vw;
        font-weight: 600;
        // height: 5vw;
        // text-align: center;
        // line-height: 5vw;
      }

      .body-fome {
        // margin-top: 2vw;
        width: 100%;
        // height: 60vh;
        overflow: auto;
        background-color: #fff;

        .body-list {
          width: 100%;
          // height: 100%;
          margin-top: 2vw;
          // height: 100%;
        }

        .listname {
          // overflow: auto;
          // width: 100%;
          // height: 100%;
        }
      }

      // height: 10vw;
      // background-color: #fff;
    }
  }
}

.zhuce {
  width: 100%;
  text-align: center;
  color: #0075ff;
  text-decoration: underline;
  cursor: pointer;
}

.button {
  width: 100%;
  height: 6vh;
}

.inputlist {
  height: 6vh;
}

.cascader {
  height: 6vh !important;
}

.imgsdiv {
  // height: 6vw;
  cursor: pointer;
  margin-left: 1vw;

  img {
    height: 1.8vw;
  }
}

.Loading {
  position: fixed;
  left: 50%;
  top: 40%;
}

.formlist {
  // height: 50vh;
}

// 手机布局
/* 平板设备样式 (包括iPad) */
@media (min-width: 768px) and (max-width: 1024px) {
  .inputlist {
    height: 3vh;
  }

  .body-logo {
    position: absolute;
    top: 2vw;
    left: 2vw;

    // background-color: pink;
    img {
      width: 15vw;
      height: 5vw;
      // background-color: pink;
      // object-fit: cover;
    }
  }

  .button {
    width: 100%;
    height: 3vh;
  }

  .Loading {
    position: fixed;
    left: 50%;
    top: 45%;
  }
}

/* 针对小屏幕的额外调整 ipd*/
@media (max-width: 767px) {
  .Loading {
    position: fixed;
    left: 40%;
    top: 45%;
  }

  .body-logo {
    position: absolute;
    top: 2vw;
    left: 2vw;

    // background-color: pink;
    img {
      width: 20vw;
      height: 7vw;
      // background-color: pink;
      // object-fit: cover;
    }
  }

  .button {
    // width: 100%;
    height: 10vw;
  }

  .bodylogin {
    display: block !important;

    // width: 50vw;
    .body-left {
      width: 100% !important;
      height: 100% !important;
      border-radius: 2vw 0 0 2vw;

      .imgbody {
        width: 100%;
        height: 100%;
      }

      // background-color: blue;
    }

    .body-right {
      width: 92% !important;
      height: 100% !important;
      border-radius: 2vw 2vw 2vw 2vw !important;
      background-color: pink;

      .imgbody {
        width: 100%;
        height: 100%;
      }

      .body-top {
        font-size: 5vw !important;
      }

      // background-color: blue;
    }
  }

  // .body-right{
  //   width: 60%;
  // }
  .imgsdiv {
    height: 6vw;
    cursor: pointer;
    margin-left: 1vw;

    img {
      height: 1.8vw;
      width: 100%;
      height: 100%;
    }
  }
}
</style>
